package com.bdqn.auth;

import com.bdqn.pojo.User;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * AuthServiceImpl
 *
 * @author LILIBO
 * @since 2023-02-23
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录（获取Token）
     *
     * @param user
     * @return
     */
    @Override
    public String login(User user) {
        if (Objects.isNull(user)) {
            throw new RuntimeException("提交的验证数据有误");
        }
        // 由SpringSecurity框架进行账号密码验证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 验证通过，获取认证主体
        SecurityUser securityUser = (SecurityUser) authenticate.getPrincipal();
        // 通过UserDetails中保存的业务用户对象获取ID生成Token，同时将登录用户对象数据存储到Redis，以备其他接口调用时，通过Token中的UID获取并验证
        String token = JWTAuth.generateJWT(securityUser);
        // 将登录用户对象数据存储到Redis，以备其他接口调用时，通过Token中的UID获取并验证
        // JedisUtil.getJedis().setex();
        return token;
    }

}
